package com.bit.librarymanagementsystem.interceptor;
import com.bit.librarymanagementsystem.Constant.Constant;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 目标方法执行前执行
     */
    @Override
    public  boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception{
        log.info("登录拦截器开始进行拦截校验");
        HttpSession session=request.getSession(false);
        if(session==null|| !StringUtils.hasLength((String) session.getAttribute(Constant.SESSION_LOGIN_USER_NAME))){
            //用户未登录
            response.setStatus(401);
            response.setContentType("text/html;charset=utf-8");
            response.getOutputStream().write("用户未登录".getBytes(StandardCharsets.UTF_8));
            log.info("用户未登录，进行拦截");
            return false;
        }
        return true;
    }

    /**
     * 在目标方法后执行
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                            ModelAndView modelAndView)throws Exception{

    }


    /**
     * 在视图渲染后执行
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                          Exception ex)throws Exception{

    }




}
